package recortes;

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.geom.*;
import java.util.Date;
import java.util.logging.*;
import java.text.*;
import javax.swing.filechooser.*;

public class Main { 
    private static JDialog dialog;
    private static JLabel text;
    private static Logger logger = Logger.getLogger("recortes.Main");
    
    public static void main( String [] args ) throws AWTException { 

        final JFrame frame = new JFrame();
        frame.setUndecorated( true );
        frame.setAlwaysOnTop( true );
        //AWTUtilitiesWrapper.setWindowOpaque( frame, false );
        AWTUtilitiesWrapper.setWindowOpacity( frame, 0.4f );
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize( d );// new Dimension( d.width, d.height - 100 ) );
        final JLabel label = new JLabel();
        label.setOpaque( false );
        label.setIcon( new ImageIcon( loadTranslucentImage() ));
        frame.add(  label );
        frame.setVisible( true );
        frame.addMouseListener( new MouseAdapter() {
            public void mouseReleased( MouseEvent e ) { 
                try {
                    isDragging = false;
                    logger.info( "isDragging = " + isDragging );
                    if( result == null ) {
                        return ;
                    }
                    
                    String baseDir = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
                    MessageFormat f = new MessageFormat("snip-{0,date,dd-MM-yy-hh-mm-ss}.png" );
                    String filePathName = f.format( new Object[]{new Date()});


                    logger.info( filePathName );
                    ImageIO.write( result, "png", new File( baseDir +  "/"+ filePathName ) ); //new File( filePathName ) );
                    text.setText("<html>&nbsp;&nbsp;&nbsp;Image saved in:<br>&nbsp;&nbsp;&nbsp;<font size=11>" + filePathName + "</font>&nbsp;&nbsp;&nbsp;</html>");
                    SwingUtilities.invokeLater( new Runnable() { 
                        public void run() {
                            dialog.validate();
                            dialog.pack();
                            Shape shape = new RoundRectangle2D.Double(0, 0, dialog.getWidth(), dialog.getHeight(), 30, 30);
                            AWTUtilitiesWrapper.setWindowShape( dialog, shape );
                            dialog.setLocationRelativeTo( frame );
                            dialog.setLocation( dialog.getLocation().x, 100 );
                            dialog.setVisible( true );
                            MouseMotionListener e = new MouseMotionAdapter() {
                                int count = 0;
                                public void mouseMoved( MouseEvent e ) {
                                    logger.info( e.toString()  );
                                    if( count++ < 10 ) { 
                                        return;
                                    }
                                    System.exit(0);
                                }
                            };
                            frame.addMouseMotionListener( e );
                            dialog.addMouseMotionListener( e );
                        }
                    });


                        boolean visibility = false;
                        int times = 15; // tenia 8....
                        //float increment = 1.0f / times;
                        float increment = 0.025f;
                        float current = visibility ? 0.0f: 0.4f;
                        int direction = visibility ? 1: -1;
                        int sleepTime = visibility ? 10 : 25;
                        for( int i = 0 ; i < times ; i++ ) try { 
                            current += ( direction * increment );
                            if( current < 0 ) { 
                                current = 0;
                            }
                           // AWTUtilitiesWrapper.setWindowOpacity( this,  current );
                            logger.info(" current = " + current );
                            AWTUtilitiesWrapper.setWindowOpacity( frame, current );
                            Thread.currentThread().sleep( sleepTime  );
                        } catch ( InterruptedException ie ) {}


                } catch ( IOException ioe ) { 
                }
            }
        });
        dialog = new JDialog( frame );
        dialog.setUndecorated( true );
        AWTUtilitiesWrapper.setWindowOpaque( dialog, false );
        AWTUtilitiesWrapper.setWindowOpacity( dialog, 1.0f );
        ((JPanel)dialog.getContentPane()).setOpaque( false );
        //dialog.getContentPane().setLayout( new GridLayout(1,1));
        text = new JLabel("   Drag to create the  snippet   ");
        text.setFont( new Font(Font.SANS_SERIF,  Font.PLAIN , 33 ));
        text.setBackground( new Color( 0,0,0,220 ));
        text.setForeground( new Color( 255,255,255,255 ));
        text.setOpaque( true );
        dialog.add( text );
        dialog.pack();
        dialog.setLocationRelativeTo(frame);
        dialog.setLocation( dialog.getLocation().x, 100 );
        Shape shape = new RoundRectangle2D.Double(0, 0, dialog.getWidth(), dialog.getHeight(), 30, 30);
        AWTUtilitiesWrapper.setWindowShape( dialog, shape );
        dialog.setVisible( true );

        frame.addMouseMotionListener( new MouseAdapter() {
            public void mouseDragged( MouseEvent e ) { 
                
                try { 
                    x = e.getPoint().x;
                    y = e.getPoint().y;
                    if( !isDragging ) { 
 
                        boolean visibility = false;
                        int times = 4; // tenia 8....
                        //float increment = 1.0f / times;
                        float increment = 0.1f;
                        float current = visibility ? 0.0f: 0.4f;
                        int direction = visibility ? 1: -1;
                        int sleepTime = visibility ? 10 : 5;
                        for( int i = 0 ; i < times ; i++ ) try { 
                            current += ( direction * increment );
                           // AWTUtilitiesWrapper.setWindowOpacity( this,  current );
                            logger.info(" current = " + current );
                            AWTUtilitiesWrapper.setWindowOpacity( frame, current );
                            Thread.currentThread().sleep( sleepTime  );
                        } catch ( InterruptedException ie ) {}
                        dialog.setVisible( false );
                        logger.info( "isDragging = " + isDragging );
                        x0 = x;
                        y0 = y;
                       isDragging = true;
        try { 
        Robot robot = new Robot();
        loaded = robot.createScreenCapture( new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() ) );
        } catch( AWTException a ){
        }
        label.setIcon( new ImageIcon( loadTranslucentImage() ));
        SwingUtilities.invokeLater( new Runnable() {
            public void run() { 

                        boolean visibility = true;
                        int times = 8; // tenia 8....
                        float increment = 1.0f / times;
                        float current = visibility ? 0.0f: 1.0f;
                        int direction = visibility ? 1: -1;
                        int sleepTime = visibility ? 10 : 50;
                        for( int i = 0 ; i < times ; i++ ) try { 
                            current += ( direction * increment );
                           // AWTUtilitiesWrapper.setWindowOpacity( this,  current );
                            AWTUtilitiesWrapper.setWindowOpacity( frame, current );
                            Thread.currentThread().sleep( sleepTime  );
                        } catch ( InterruptedException ie ) {}
            }
        });
                        logger.info( "isDragging = " + isDragging );
                        x0 = x;
                        y0 = y;
                    }
                    //logger.info( e );
                    label.setIcon( new ImageIcon( loadTranslucentImage() ));
                } catch( AWTException awte ) {}

                }
            public void mouseReleased( MouseEvent e ) { 
                logger.info( e.toString() );
            }
        });
    }  
    private static boolean isDragging;
    private static int x0;
    private static int y0;
    private static int x;
    private static int y;
    private static BufferedImage loaded;
    private static BufferedImage result;
    static { 
    }
    public static BufferedImage loadTranslucentImage() throws AWTException {  
        // Load the image  

        if( loaded != null ) { 

        BufferedImage original = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TRANSLUCENT);  
        BufferedImage snip     = new BufferedImage( x-x0<=0?1:x-x0, y-y0<=0?1:y-y0  , BufferedImage.OPAQUE    );  

        Graphics2D o = original.createGraphics();
        o.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.4f ));
        o.drawImage( loaded, null, 0 , 0 );


        Graphics2D s = snip.createGraphics();
        s.drawImage( loaded, null, x*-1 + x-x0 ,y0*-1);
        s.dispose();

        result = snip;



        o.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 1.0f ));
        o.drawImage( snip, null , x0, y0 );
        Color color  = o.getColor();
        o.setColor( Color.red );
        o.drawRect( x0, y0,  snip.getWidth() -1 , snip.getHeight() -1  );
        o.drawRect( x0+1, y0+1,  snip.getWidth() -3 , snip.getHeight() -3  );
        o.setColor( color );
        o.dispose();

        return original;
        } else { 
            BufferedImage original = new BufferedImage(1200, 800, BufferedImage.TRANSLUCENT);  
            final Graphics2D o = original.createGraphics();
            Color color  = o.getColor();
            o.setColor( Color.red );
            o.drawRect( x0, y0,   x-x0<=0?1:x-x0 -1 , y-y0<=0?1:y-y0 -1 );
            o.drawRect( x0+11, y0+11,   x-x0<=0?1:x-x0 -3, y-y0<=0?1:y-y0 -3 );
            o.setColor( color );
            o.dispose();
            logger.info( "Returning that version ");
        return original;
        }
    }
}
